package com.bw.gmall.realtime.Day0921;

import com.alibaba.fastjson.JSONObject;
import com.bw.gmall.realtime.bean.TradePaymentWindowBean;
import com.bw.gmall.realtime.utils.DateFormatUtil;
import com.bw.gmall.realtime.utils.MyKafkaUtil;
import com.bw.gmall.realtime.utils.TimestampLtz3CompareUtil;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessAllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;

/*
*
uid 分组     取出第一次的
*
*
* */
//从 Kafka 读取交易域支付成功主题数据，统计支付成功独立用户数和首次支付成功用户数。
public class DwsTradePaymentSucWindow_b {

    public static void main(String[] args) throws Exception {

        //1.创建流式环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        //2.设置并行度
        env.setParallelism(1);
        //3.设置检查点
        //4.加载数据源
        DataStreamSource<String> addSource = env.addSource(MyKafkaUtil.getFlinkKafkaConsumer("dwd_trade_pay_detail_suc", "DwsTradePaymentSucWindow_b_xxx"));
        //5.保留最新数据 最全数据
        SingleOutputStreamOperator<JSONObject> map = addSource.flatMap(new FlatMapFunction<String, JSONObject>() {
            @Override
            public void flatMap(String value, Collector<JSONObject> out) throws Exception {
                JSONObject jsonObject = JSONObject.parseObject(value);
                out.collect(jsonObject);
            }
        });

        KeyedStream<JSONObject, String> keyedStream = map.keyBy(a -> a.getString("order_detail_id"));
        SingleOutputStreamOperator<JSONObject> process = keyedStream.process(new KeyedProcessFunction<String, JSONObject, JSONObject>() {
            ValueState<JSONObject> valueState;

            @Override
            public void open(Configuration parameters) throws Exception {

                valueState = getRuntimeContext().getState(new ValueStateDescriptor<JSONObject>("valueState", JSONObject.class));
            }

            @Override
            public void processElement(JSONObject value, Context ctx, Collector<JSONObject> out) throws Exception {

                JSONObject v = valueState.value();
                if (v == null) {
                    valueState.update(value);
                    //触发定时器   5l
                    ctx.timerService().registerProcessingTimeTimer(ctx.timerService().currentProcessingTime() + 5000l);
                } else {

                    String jl_row_op_ts = value.getString("row_op_ts");
                    String v_row_op_ts = v.getString("row_op_ts");
                    if (TimestampLtz3CompareUtil.compare(v_row_op_ts, jl_row_op_ts) != 1) {
                        valueState.update(value);
                    }

                }

            }

            @Override
            public void onTimer(long timestamp, OnTimerContext ctx, Collector<JSONObject> out) throws Exception {
                super.onTimer(timestamp, ctx, out);
                JSONObject value = valueState.value();
                out.collect(value);
                valueState.clear();
            }
        });
//
        SingleOutputStreamOperator<JSONObject> wt = process.assignTimestampsAndWatermarks(WatermarkStrategy.<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(2)
        ).withTimestampAssigner(new SerializableTimestampAssigner<JSONObject>() {
            @Override
            public long extractTimestamp(JSONObject element, long recordTimestamp) {
                return DateFormatUtil.toTs(element.getString("callback_time"), true);
            }
        }));
        //wt  统计支付成功独立用户数和首次支付成功用户数。
        SingleOutputStreamOperator<TradePaymentWindowBean> process1 = wt.keyBy(a -> a.getString("user_id"))
                .process(new KeyedProcessFunction<String, JSONObject, TradePaymentWindowBean>() {
                    ValueState<String> valueStates;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        valueStates = getRuntimeContext().getState(new ValueStateDescriptor<String>("valueStates", String.class));
                    }

                    @Override
                    public void processElement(JSONObject value, Context ctx, Collector<TradePaymentWindowBean> out) throws Exception {


                        String stateDate = valueStates.value();
                        String jlDate = value.getString("callback_time").split(" ")[0];

                        Long uvPay = 0l;
                        Long firstPay = 0l;

                        if (stateDate == null) {
                            uvPay = 1l;
                            firstPay = 1l;
                            valueStates.update(jlDate);
                        } else {

                            if (!jlDate.equals(stateDate)) {
                                uvPay = 1l;
                                valueStates.update(jlDate);
                            }
                        }
                        if (uvPay != 0l) {
                            out.collect(new TradePaymentWindowBean("", "", uvPay, firstPay, null));
                        }


                    }
                });

        //分组开窗聚合
        SingleOutputStreamOperator<Object> reduce = process1.windowAll(TumblingEventTimeWindows.of(Time.seconds(10l)))
                .reduce(new ReduceFunction<TradePaymentWindowBean>() {
                    @Override
                    public TradePaymentWindowBean reduce(TradePaymentWindowBean value1, TradePaymentWindowBean value2) throws Exception {
                        value1.setPaymentSucUniqueUserCount(value1.getPaymentSucUniqueUserCount() + value2.getPaymentSucUniqueUserCount());
                        value1.setPaymentSucNewUserCount(value1.getPaymentSucNewUserCount() + value2.getPaymentSucNewUserCount());
                        return value1;
                    }
                }, new ProcessAllWindowFunction<TradePaymentWindowBean, Object, TimeWindow>() {
                    @Override
                    public void process(Context context, Iterable<TradePaymentWindowBean> values, Collector<Object> out) throws Exception {

                        TradePaymentWindowBean next = values.iterator().next();

                        next.setTs(System.currentTimeMillis());
                        next.setEdt(DateFormatUtil.toYmdHms(context.window().getEnd()));
                        next.setStt(DateFormatUtil.toYmdHms(context.window().getStart()));

                        out.collect(next);
                    }
                });
        reduce.print("-------------->");
        env.execute();

    }

}
